package com.example.demo.controller;
import org.jooby.filewatcher.FileWatcher;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.io.File;
import java.util.stream.Collectors;

@RestController
public class FileWatcher {
    @Value("${file.directory}")
    private String directory;

    private org.jooby.filewatcher.FileWatcher fileWatcher;

    @GetMapping("/api/files")
    public List<String> getFiles() {
        File dir = new File(directory);
        File[] files = dir.listFiles();
        return Arrays.stream(files)
                .filter(file -> !file.isDirectory())
                .map(file -> file.getName())
                .collect(Collectors.toList());
    }

    @PostConstruct
    public void init() {
        fileWatcher = new org.jooby.filewatcher.FileWatcher(directory, filePath);
    }

    @PreDestroy
    public void destroy() throws InterruptedException {
        fileWatcher.stopWatching();
    }
}
